package com.production.CoursePlatform.service;

import com.production.CoursePlatform.dto.NoticeWithIsReadDTO;
import com.production.CoursePlatform.entity.Notice;
import com.production.CoursePlatform.mapper.NoticeMapper;
import com.production.CoursePlatform.response.ApiResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.IService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class NoticeService {

    @Autowired
    private NoticeMapper noticeMapper;
    @Autowired
    private StudyingService studyingService;

    // 增加通知
    @Transactional
    public ApiResponse addNotice(Notice notice) {
        int result = noticeMapper.insertNotice(notice); // 返回受影响的行数

        if (result == 1) {
            // 插入成功
            int unreadNumber = studyingService.getStudentNumberOfCtID(notice.getCtID());
            noticeMapper.setUnreadNumber(notice.getCnID(), unreadNumber);
            return new ApiResponse("Notice created successfully", true);
        } else {
            // 插入失败
            return new ApiResponse("Notice creation failed", false);
        }
    }

    // 根据 cn_id 删除通知
    @Transactional
    public ApiResponse deleteNoticeById(int cnID) {
        int rows = noticeMapper.deleteNoticeByCnID(cnID);
        if (rows > 0) {
            return new ApiResponse("Notice deleted successfully", true);
        } else {
            return new ApiResponse("Failed to delete notice", false);
        }
    }

    // 修改通知
    @Transactional
    public ApiResponse updateNotice(Notice notice) {
        int rows = noticeMapper.updateNotice(notice);
        if (rows > 0) {
            return new ApiResponse("Notice updated successfully", true);
        } else {
            return new ApiResponse("Failed to update notice", false);
        }
    }

    // 根据 cn_id 查找通知
    public Notice findNoticeById(int cnID) {
        return noticeMapper.selectNoticeByCnID(cnID);
    }

    // 根据 ct_id 查找所有通知
    public List<Notice> findNoticesByCtId(int ctID) {
        return noticeMapper.selectNoticesByCtID(ctID);
    }

    // 查找所有通知
    public List<NoticeWithIsReadDTO> findAllNoticesBySID(int sID) {
        return noticeMapper.findAllNoticesBySID(sID);
    }

}
